<template>
    <text>{{text}}</text>
</template>
<script>
let timeEr = null;
export default {
    props: {
        time: {
            type: Number,
            default: undefined
        },
        endText: {
            type: String,
            default: ''
        }
    },
    watch: {
        time(val) {
            this.num=Math.ceil(val)
            this.$nextTick(() => {
                this.createTimeEr();
            })
        }
    },
    data() {
        return {
            num:undefined,
            text: ''
        };
    },
    created() {
        this.num=Math.ceil(this.time)
        this.$nextTick(() => {
            this.createTimeEr();
        })
    },
    beforeDestroy() {
        console.log('beforeDestroy');
        if (timeEr) {
            clearInterval(timeEr);
            timeEr = null;
        }
    },
    methods: {
        createTimeEr() {
            if(this.num===undefined){return;}
            if (this.num > 0) {
                if (timeEr) {
                    clearInterval(timeEr);
                    timeEr = null;
                }
                timeEr = setInterval(() => {
                    const t = this.num--;
                    if (t <= 0) {
                        clearInterval(timeEr);
                        timeEr=null;
                        this.$emit('end');
                    }else{
                        this.text=this.getTimeText(t);
                    }
                }, 1000)
            } else {
                if (timeEr) {
                    clearInterval(timeEr);
                    timeEr = null;
                }
                if(this.num>-3600){
                    timeEr = setInterval(() => {
                        const t = Math.abs(this.num--);
                        if (t >= 3600) {
                            clearInterval(timeEr);
                            timeEr=null;
                        }else{
                            this.text = `超时${this.getTimeText(t)}`;
                        }
                    }, 1000)
                }else{
                    if (this.endText) {
                        this.text = this.endText;
                    }
                }
            }
        }
    }
}
</script>
<style lang="scss" scoped></style>